<?php

namespace App\Http\Middleware;

use App\Permission;
use Closure;
use Illuminate\Support\Facades\Auth;

class AuthPermission
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (Auth::check()) {
            $user = $request->user();
            if($user->email==='280498307@qq.com') return $next($request);
            $permission = $this->getPermission($request);
            if (!empty($permission) && $user->hasPermissionTo($permission['id'])) {
                return $next($request);
            }
            return response()->json(['status' => 403001, 'message' => '没有权限'], 403);
        } else {
            return response()->json(['status' => 401, 'message' => '未登录'], 401);
        }
    }

    protected function getPermission($request)
    {
        $route = '/' . $request->path();
        $uri = '/' . $request->route()->uri();
        $dbroute = substr($route, strlen(env('PREFIX')));
        $dburi = substr($uri, strlen(env('PREFIX')));
        $method = $request->method();
        $permissionRepo = new Permission();
        $perg = '/\{[\w]*\?{0,1}\}/';
        if ($route === $uri) {
            $where = ['method' => strtolower($method), 'path' => $dbroute];
            $permission = $permissionRepo->where($where)->first();
        } else {
            $where = ['method' => $method, 'path' => preg_replace($perg, '*', $dburi)];
            $permission = $permissionRepo->where($where)->first();  //这个主要是解决  ‘/users/{id}/index’ 这一类的路由，在数据库中应该存‘/users/*/index’
        }
        return $permission;
    }
}
